<?php
namespace Alipay\EasySDK;

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
use Arr;
use Alipay\EasySDK\Contracts\OrderInterface;

class Alipay
{
    public $appName;

    public function setAppName($appName)
    {
        $this->appName = $appName;
    }

    public function page(OrderInterface $order)
    {
        Factory::setOptions(self::getOptions());
        $returnUrl = config("alipay.{$this->appName}.returnUrl");
        $result = null;
        try {
            //2. 发起API调用
            $result = Factory::payment()->page()->pay(
                $order->getName(),
                $order->getOrderNo(),
                floatval($order->getMoney()),
                $returnUrl
            );
            //3. 处理响应或异常
            return response()->ajax($result);
        } catch (Exception $e) {
            return response()->error("调用失败，". $e->getMessage(). PHP_EOL);
        }
    }

    //验证参数
    public function verifyNotify($params)
    {
        Factory::setOptions(self::getOptions());
        $verifyRes = Factory::payment()->common()->verifyNotify($params);
        return !!$verifyRes;
    }

    protected function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $config = config("alipay.{$this->appName}");
        $options->appId = Arr::get($config, 'appId');
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = Arr::get($config, 'merchantPrivateKey');
        // 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt;
        $options->alipayCertPath = Arr::get($config, 'alipayCertPath');
        // 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt;
        $options->alipayRootCertPath = Arr::get($config, 'alipayRootCertPath');
        // 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt;
        $options->merchantCertPath = Arr::get($config, 'merchantCertPath');
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        // $options->alipayPublicKey = '<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->';
        //可设置异步通知接收服务地址（可选）
        $options->notifyUrl = Arr::get($config, 'asyncNotifyUrl');
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        //$options->encryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->";
        return $options;
    }
}